/**
 * @UUIDIdentifier.java  COPYRIGHT xiaojian
 * 
 * Created on 2018年3月15日 上午10:42:19
 */
package xj.toolkit.util;

import java.io.Serializable;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;

import com.google.common.base.Preconditions;

/**
 * @author <a href="mailto:cxj2000@gmail.com">xiaojian.cao</a>
 *
 */
public class UUIDIdentifier implements Identifier<UUID>, Serializable {

	private static final long serialVersionUID = 7399069432138552968L;

	private UUID identification = UUID.randomUUID();

	@Override
	public UUID getValue() {
		return identification;
	}

	@Override
	public void setVaule(UUID t) {
		Preconditions.checkArgument(t != null);

		this.identification = t;
	}

	@Override
	public String valueAsString() {
		return identification != null ? identification.toString() : null;
	}

	@Override
	public int valueAsInt() {
		throw new UnsupportedOperationException("UUID cannt as int.");
	}

	@Override
	public byte[] valueAsByte() {
		if (identification == null) {
			return new byte[0];
		}
		return valueAsString().getBytes();
	}

	@Override
	public UUIDIdentifier fromSrting(String id) {
		Preconditions.checkArgument(StringUtils.isNoneBlank(id));

		this.identification = UUID.fromString(id);
		return this;
	}

	@Override
	public UUIDIdentifier fromInt(int id) {
		throw new UnsupportedOperationException("UUID cannt as int.");
	}

	/**
	 * 
	 */
	@Override
	public int length() {
		return identification != null ? valueAsString().length() : -1;
	}

	@Override
	public boolean equals(Object other) {
		Preconditions.checkArgument(other != null);

		if (!(other instanceof UUIDIdentifier)) {
			return false;
		}

		UUIDIdentifier ii = (UUIDIdentifier) other;
		return ii.getValue().compareTo(getValue()) == 0;
	}

	@Override
	public int hashCode() {
		return this.identification != null ? this.identification.hashCode() : 0;
	}

	@Override
	public UUIDIdentifier fromByte(byte[] bArray) {
		Preconditions.checkArgument(bArray != null && bArray.length > 0);

		fromSrting(new String(bArray));
		return this;
	}

	public String toString() {
		return "UUIDIdentifier[value=" + this.identification + "]";
	}

}
